package cn.springcloud.fix.auth.service;

import cn.springcloud.fix.auth.bo.UserDetail;
import cn.springcloud.fix.auth.dao.entity.Role;
import cn.springcloud.fix.auth.dao.entity.User;
import cn.springcloud.fix.auth.dao.entity.UserRole;
import cn.springcloud.fix.auth.dao.mapper.RoleMapper;
import cn.springcloud.fix.auth.dao.mapper.UserMapper;
import cn.springcloud.fix.auth.dao.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    // @Autowired
    // private List<IntegrationAuthenticator> authenticators;

    /**
     * 用户登录时自动调用
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getAccount, username));
        if (user == null) throw new UsernameNotFoundException("账户不存在！");

        List<UserRole> userRoles = userRoleMapper.selectList(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, user.getId()));
        UserDetail userDetail = assembleUserDetail(user);
        if (CollectionUtils.isNotEmpty(userRoles)) {
            List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList());
            List<Role> roleList = roleMapper.selectList(Wrappers.<Role>lambdaQuery().in(Role::getId, roleIds));
            Set<GrantedAuthority> authorities = roleList.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toSet());
            userDetail.setAuthorities(authorities);
        }
        return userDetail;
    }

    private UserDetail assembleUserDetail(User user) {
        //EBL-有效，DEL-无效，LCK-锁定
        UserDetail userDetail = new UserDetail();
        userDetail.setUsername(user.getAccount());
        userDetail.setPassword(user.getPassword());
        userDetail.setEnabled(!Objects.equals(user.getStatus(), "DEL"));
        userDetail.setAccountNonLocked(!Objects.equals(user.getStatus(), "LCK"));
        return userDetail;
    }
}
